/**
 * 常量
 */
var constant = {
  host:"http://sale.518woyaofa.com/"
}

/**
 * 接口
 */
var BASE_URL = window.location.host?'/yaoyiyao/':'http://localhost:9090/yaoyiyao/';
var API = {
  login:BASE_URL+'login/login',
  checkLogin:BASE_URL+'login/checkLogin',

  addPenson:BASE_URL+'yao/addPenson',
  addPensonCount:BASE_URL+'yao/addPensonCount',

  addHuodong:BASE_URL+'manager/addHuodong',
  deHuodong:BASE_URL+'manager/deHuodong',
  getHuodong:BASE_URL+'manager/getHuodong',
  getAllHuodong:BASE_URL+'manager/getAllHuodong',
  deAllHuodong:BASE_URL+'manager/deAllHuodong',
  isbeginHuodong:BASE_URL+'manager/isbeginHuodong',
}

/**
 * 工具类
 */
var utils = {
  //ajax
  ajax:function(params){
    if (typeof $ == "undefined") {
      throw new Error("没有引入jquery");
    }

    var p = Object.assign({},params);

    //携带cookie
    // params.xhrFields = { withCredentials: true };
    p.contentType = p.contentType?p.contentType:"application/json;charset=utf-8";
    p.data = p.data?JSON.stringify(p.data):null;
    p.type = p.type?p.type:'POST';
    p.dataType = "json";

    p.success = function(data){
      // console.log(data)
      params.success&&params.success(data)
    }
    
    $.ajax(p)
  },
  //获取url参数
  getUrlParam:function(name) {
    var result = location.search.match(new RegExp("[\?\&]" + name+ "=([^\&]+)","i"));
    if(result == null || result.length < 1){
      return null;
    }
    return result[1];
  },
  setSession:function(name,data){
    window.sessionStorage.setItem(name,JSON.stringify(data));
  },
  getSession:function(name){
    return JSON.parse(window.sessionStorage.getItem(name));
  },
  setLocal:function(name,data){
    window.localStorage.setItem(name,JSON.stringify(data));
  },
  getLocal:function(name){
    return JSON.parse(window.localStorage.getItem(name));
  },
  urlParamsName:'urlParams',
  go:function(url,params){
    this.setSession(this.urlParamsName,params);
    window.location.href = url;
  },
  getUrlParamBySession:function(){
    var urlParams = this.getSession(this.urlParamsName);
    window.sessionStorage.removeItem(this.urlParamsName);
    return urlParams;
  },
  //微信支付
  wxPay:function(obj){
    function onBridgeReady(){
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId":constant.appid,     //公众号名称，由商户传入     
            "timeStamp":obj.data.timeStamp,         //时间戳，自1970年以来的秒数     
            "nonceStr":obj.data.nonceStr, //随机串     
            "package":"prepay_id="+obj.data.prepay_id,     
            "signType":"MD5",         //微信签名方式：     
            "paySign":obj.data.paySign //微信签名 
        },
        function(res){
        if(res.err_msg == "get_brand_wcpay_request:ok" ){
          // 使用以上方式判断前端返回,微信团队郑重提示：
          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
          obj.success&&obj.success(res)
        }else{
          obj.error&&obj.error(res)
        }
        obj.complete&&obj.complete(res)
      }); 
    }
    if (typeof WeixinJSBridge == "undefined"){
      if( document.addEventListener ){
          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
      }else if (document.attachEvent){
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
      }
    }else{
      onBridgeReady();
    }
  },
  //微信初始化
  wxConfig:function(fn){
    utils.ajax({
      url:API.test,
      data:{
        url:window.location.href.split("#")[0]
      },
      success:function(data){
        wx.config({
          debug: false,
          appId: data.appid,
          timestamp: data.timestamp,
          nonceStr: data.noncestr,
          signature: data.signature,
          jsApiList: ["chooseWXPay", "openLocation", "getLocation"]
        });
        wx.ready(function(){
          //检查获取定位权限是否配置成功
    		  wx.checkJsApi({  
            jsApiList: ["chooseWXPay", "openLocation", "getLocation"],
            success:function(res){  
              fn&&fn(data);
            }
          });
        })
      }
    })
  },
  //加载弹窗
  loading:function(type){
    if (type) {
      if (document.getElementById('my_loading')) return;
      var dom = document.createElement('div');
      dom.id = 'my_loading';
      dom.style = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 99999;
      `;
      var img = document.createElement('img');
      img.src = './img/loading.gif';
      img.style = `
        position: absolute;
        margin: auto;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 64px;
      `;
      dom.appendChild(img);
      document.body.appendChild(dom);
    } else {
      var alert = document.getElementById('my_loading');
      alert&&alert.remove();
    }
  }
};